//
//  CustomTableViewController.m
//  quanminzhekou
//
//  Created by zxl on 15/1/13.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "CustomTableViewController.h"
#import "CommonTableViewCell.h"
#import "DetailViewController.h"
#import "CommonEngine.h"
#import "CommonCellViewModel.h"

@interface CustomTableViewController ()
@property (nonatomic) MKNetworkOperation* customOperation;
@end

@implementation CustomTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (nil == _customDataArr) {
        _customDataArr = [[NSMutableArray alloc] init];
    }
    
    self.titleLab.text = self.title;
    
    if (CustomTableViewControllerTypeNormal == self.type) {
        NSString* value = @"5";
        if ([self.title isEqualToString:@"9.9包邮"]) {
            value = @"2";
        } else if ([self.title isEqualToString:@"20封顶"]) {
            value = @"3";
        } else if ([self.title isEqualToString:@"爆款推荐"]) {
            value = @"4";
        }
        
        self.engineModel.zqStr = value;
        [self updateData];
    } else if (CustomTableViewControllerTypeFocus == self.type){
        [self.engineModel parameterBySeparatedUrlPath:self.urlPath];
        [self updateData];
    } else {
        self.engineModel.kwStr = self.keyword;
        self.viewControllerType = ViewControllerNormalType;
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}

- (void)dealloc
{
    [self.customOperation cancel];
}

#pragma mark - super
- (void)updateData {
    [super updateData];
    [self requestCustomData];
}

#pragma mark - 
- (void)requestCustomData {
    if (self.customOperation.isExecuting) {
        return;
    }
    
    NSString* path = @"";
    if (CustomTableViewControllerTypeSearch == self.type) {
        path = [[CommonEngine sharedInstance] urlPathForSearchWithDictionary:self.engineModel.dic];
    } else {
        path = [[CommonEngine sharedInstance] urlPathForDataWithDictionary:self.engineModel.dic];
    }
    
    __weak typeof(self) weakSelf = self;
    _customOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
        NSNumber* status = [result objectForKey:@"status"];
        NSNumber* count = [result objectForKey:@"count"];
        if (1 == status.integerValue) {
            
            NSMutableArray* res = [NSMutableArray new];
            
            NSArray* arr = [result objectForKey:@"res"];
            for (NSDictionary* dic in arr) {
                CommonCellModel* model = [[CommonCellModel alloc] initWithDic:dic];
                CommonCellViewModel* viewModel = [[CommonCellViewModel alloc] initWithCommonCellModel:model];
                [res addObject:viewModel];
            }
            
            if (weakSelf.engineModel.isNeedReloadData) {
                weakSelf.customDataArr = res;
                weakSelf.engineModel.isNeedReloadData = NO;
            } else {
                [weakSelf.customDataArr addObjectsFromArray:res];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                [weakSelf.tableView resetReloadMoreViewFrame];
                if (TableViewUpdateTypeRefresh == weakSelf.tableView.type) {
                    [weakSelf finishRefreshData];
                } else if (TableViewUpdateTypeReloadMore == weakSelf.tableView.type) {
                    [weakSelf finishReloadMoreDataWithIsEnd:(0 == count.integerValue)];
                }
                
                weakSelf.viewControllerType = ViewControllerNormalType;
            });
        }
    } errorHandler:^(NSError *errMsg) {
        NSLog(@"%@", errMsg);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView resetReloadMoreViewFrame];
            if (TableViewUpdateTypeRefresh == weakSelf.tableView.type) {
                [weakSelf finishRefreshData];
            } else if (TableViewUpdateTypeReloadMore == weakSelf.tableView.type) {
                [weakSelf finishReloadMoreDataWithIsEnd:NO];
            }
            
            weakSelf.viewControllerType = ViewControllerNoNetWorkType;
        });
    }];
}

#pragma mark - IBAction
- (IBAction)onTapBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.customDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommonTableViewCell *cell = (CommonTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    if ([self.title isEqualToString:@"明日预告"]) {
        cell.isHasSelectedType = NO;
    } else {
        cell.isHasSelectedType = YES;
    }
    
    CommonCellViewModel* viewModel = [self.customDataArr objectAtIndex:indexPath.row];
    [cell layoutSubviewDataWithViewModel:viewModel];
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CommonTableViewCell* cell = (CommonTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    if (cell.isSwiping) {
        return;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([self.title isEqualToString:@"明日预告"]) {
        return;
    }
    
    CommonCellViewModel* viewModel = [self.customDataArr objectAtIndex:indexPath.row];
    
    DetailViewController* controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
    controller.currentGoodsViewModel = viewModel;
    [self.navigationController pushViewController:controller animated:YES];
}

@end
